#include "gb.h"
#include <SDL/SDL.h>

// SDL_init must be called before this
//  function is used
void gb_check_input(gb_state *gb)
{
	// Default configuration
	static unsigned int a = SDLK_j;
	static unsigned int b = SDLK_k;
	static unsigned int start = SDLK_RETURN;
	static unsigned int select = SDLK_SPACE;
	static unsigned int up = SDLK_w;
	static unsigned int down = SDLK_s;
	static unsigned int left = SDLK_a;
	static unsigned int right = SDLK_d;

	unsigned char *keystates = SDL_GetKeyState(0);
	gb->P1 |= 0x0f;

	// Bit 4 = direction keys (0 = select)
	if(!(gb->P1 & 0x10))
	{
		if(keystates[right])
		{
			// Bit 0 = input right (0 = pressed)
			gb->P1 &= 0xfe;
		}
		if(keystates[left])
		{
			// Bit 1 = input left (0 = pressed)
			gb->P1 &= 0xfd;
		}
		if(keystates[up])
		{
			// Bit 2 = input up (0 = pressed)
			gb->P1 &= 0xfb;
		}
		if(keystates[down])
		{
			// Bit 3 = input down (0 = pressed)
			gb->P1 &= 0xf7;
		}
	}
	// Bit 5 = button keys (0 = select)
	else if(!(gb->P1 & 0x20))
	{
		if(keystates[a])
		{
			// Bit 0 = a button (0 = pressed)
			gb->P1 &= 0xfe;
		}
		if(keystates[b])
		{
			// Bit 1 = b button (0 = pressed)
			gb->P1 &= 0xfd;
		}
		if(keystates[select])
		{
			// Bit 2 = select (0 = pressed)
			gb->P1 &= 0xfb;
		}
		if(keystates[start])
		{
			// Bit 3 = start (0 = pressed)
			gb->P1 &= 0xf7;
		}
	}
}
